/**
 * Description: socket 客户端 - 使用read 发送信息
 * File: client_send.c |Time: 2021-04-10 08:40
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

#define BUF_SIZE 100

#define ERR(msg) do {          \
            perror(msg);        \
            printf("%s:%s:%d\n", __FILE__, __func__, __LINE__); \
            exit(EXIT_FAILURE); \
        }while(0)

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s <ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 创建socket文件描述符
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
        perror("socket error");
        return -1;
    }


    // 连接到服务器
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(atoi(argv[2]));
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (
            connect(
                sockfd, 
                (struct sockaddr *)&serveraddr, 
                sizeof(struct sockaddr)
            ) == -1
       )
    {
        ERR("connect");
    }

    // 发送信息
    char buf[BUF_SIZE];

    while(1)
    {
        printf("[to server]:");
        fgets(buf, BUF_SIZE, stdin);
        buf[strlen(buf) - 1] = '\0';
        
        int res = send(sockfd, buf, strlen(buf), 0);
        if(res == -1)
        {
            ERR("send");
        }

        if (strncmp(buf, "bye", 3) == 0) {
            memset(buf, 0, BUF_SIZE);
            recv(sockfd, buf, BUF_SIZE, 0);

            close(sockfd);

            exit(EXIT_SUCCESS);
        }

        memset(buf, 0, BUF_SIZE);

        recv(sockfd, buf, BUF_SIZE, 0);
        printf("[from server]: %s\n", buf);


        memset(buf, 0, BUF_SIZE);
    }

    return 0;
}
